import jwt
from flask import current_app
from datetime import datetime,timedelta


def get_token(payload_,expiry):
    payload = {
        'exp': expiry
    }
    payload.update(payload_)
    secret = current_app.config['SECRET_KEY']
    token = jwt.encode(payload, secret, algorithm='HS256')
    return 'JWT ' + token

def token_auth(token):
    secret = current_app.config['SECRET_KEY']
    try:
        payload = jwt.decode(token, secret, algorithms='HS256')
        return payload
    except Exception as e:
        print('token认证失败',e)
        return str(e)

def _generate_token(user,refresh=True):
    payload = {
        'id':user.uid,
        'name':user.account,
    }
    expiry = datetime.utcnow()+timedelta(hours=100000)
    token = get_token(payload,expiry)
    if refresh:
        payload.update({'refresh':True})
        expiry = datetime.utcnow()+timedelta(days=15)
        refresh_token = get_token(payload,expiry)
    else:
        refresh_token = None
    return token,refresh_token